package com.basedefence;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.res.AssetManager;

import com.e3roid.E3Activity;
import com.e3roid.drawable.sprite.AnimatedSprite;
import com.e3roid.drawable.texture.Texture.Option;
import com.e3roid.drawable.texture.TiledTexture;

public class SpriteLoader
{
	private static HashMap<String, ArrayList<AnimatedSprite>> sprites;
	
	public static void loadSprite (String imageName)
	{
		if (sprites == null)
			sprites = new HashMap<String, ArrayList<AnimatedSprite>>();
		
		ArrayList<AnimatedSprite> animations = new ArrayList<AnimatedSprite>();
		
		TiledTexture texture;
		
		int frameWidth = -1;
		int frameHeight = -1;
		int xindex = -1;
		int yindex = -1;
		int border = -1;
		int margin = -1;
		
		String spriteName = imageName + ".spr";
		
		try {
			AssetManager am = E3Activity.getCurrentActivity().getAssets();
			InputStream is = am.open(spriteName);
			
			DataInputStream spriteStream = new DataInputStream(is);
			
			frameWidth = spriteStream.readShort();
			frameHeight = spriteStream.readShort();
			xindex = spriteStream.readShort();
			yindex = spriteStream.readShort();
			border = spriteStream.readShort();
			margin = spriteStream.readShort();
			
			texture = TextureManager.getTexture(imageName, frameWidth, frameHeight, xindex, yindex, border, margin, Option.DEFAULT);
			
			byte animAmount = spriteStream.readByte();
			for (int i = 0; i < animAmount; i++) 
			{
				ArrayList<AnimatedSprite.Frame> frames = new ArrayList<AnimatedSprite.Frame>();
				short framesAmount = spriteStream.readShort();
				
				for (int j = 0; j < framesAmount; j++) 
				{
					short frameX = spriteStream.readShort();
					short frameY = spriteStream.readShort();
					
					frames.add(new AnimatedSprite.Frame(frameX, frameY));
				}
				AnimatedSprite spr = new AnimatedSprite(texture, 0, 0);
				spr.animate(100, frames);
				animations.add(spr);
			}
			
			sprites.put(imageName, animations);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static AnimatedSprite getAnimation (String imageName, int animIndex)
	{
		if (sprites == null)
			return null;
		
		ArrayList<AnimatedSprite> spriteAnimations = sprites.get(imageName);
		return spriteAnimations == null ? null : spriteAnimations.get(animIndex).clone();
	}
	
	public static void unloadSprite (String imageName)
	{
		sprites.remove(imageName);
	}
}
